package com.dubito.composenote

import android.app.Application
import android.content.Intent
import android.net.Uri
import androidx.room.Room
import com.dubito.composenote.data.NotesDao
import com.dubito.composenote.data.NotesDatabase

/**
 * author: LiLiang
 * createTime: 2022/10/6-11:27
 * remark:
 **/
class ComposeNoteApp : Application() {

    private var db: NotesDatabase? = null

    init {
        instance = this
    }

    private fun getDb(): NotesDatabase {
        return if (db != null) {
            db!!
        } else {
            db = Room.databaseBuilder(
                instance!!.applicationContext,
                NotesDatabase::class.java,
                Constants.DATABASE_NAME
            ).fallbackToDestructiveMigration().build()
            db!!
        }
    }

    companion object {

        private var instance: ComposeNoteApp? = null

        fun getDao(): NotesDao {
            return instance!!.getDb().NotesDao()
        }

        fun getUriPermission(uri: Uri) {
            instance!!.applicationContext.contentResolver.takePersistableUriPermission(
                uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
        }
    }
}